package cn.edu.zju.gis.disasterBE.sever.service;

import cn.edu.zju.gis.disasterBE.sever.dao.NewsDAO;
import cn.edu.zju.gis.disasterBE.sever.entity.News;
import cn.edu.zju.gis.disasterBE.sever.entity.global.MyResponse;
import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class NewsService {
    protected final NewsDAO newsDAO;
    public MyResponse<News> articlePost(String json)
    {
        MyResponse<News> myResponse = new MyResponse<>();
        News news = JSON.parseObject(json,News.class);
        myResponse.setState(false);
        if (news.getTitle().length() >= 50)
        {
            myResponse.setMsg("The title is too long!");
            return myResponse;
        }
        else if (news.getTitle().length() <= 1)
        {
            myResponse.setMsg("The title is too short!");
            return myResponse;
        }
        myResponse.setData(news);
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        news.setPostTime(timestamp);
        if(newsDAO.articlePost(news))
        {
            myResponse.setMsg("Post successfully");
            myResponse.setState(true);
        }
        else
        {
            myResponse.setMsg("Fail to post");
        }
        return myResponse;
    }

    public MyResponse<List<News>> articleGetAll()
    {
        List<News> news = newsDAO.getArticleAll();
        MyResponse<List<News>> myResponse = new MyResponse<>();
        myResponse.setData(news);
        myResponse.setState(true);
        myResponse.setMsg("Read news successfully");
        return myResponse;
    }

    public MyResponse<String> articleDelete(Integer nid)
    {
        int ans = newsDAO.deleteArticleByID(nid);
        MyResponse<String> myResponse = new MyResponse<>();
        if(ans == 0)
        {
            myResponse.setState(false);
        }
        else
        {
            myResponse.setState(true);
        }
        return myResponse;
    }
}

